<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24">
        <SearchForm
          v-show="showSearch"
          v-model="queryParams"
          :options="options.formOps"
          @onQuery="getList"
        >
        </SearchForm>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              v-hasPermi="['preventionPlan:create']"
              >新增</el-button
            >
          </el-col>

          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>
        <Table
          ref="table"
          :auto-featch="true"
          :fetch-data="fetchData"
          :options="options.table"
          :actionWidth="250"
        >
          <template #userNames="{ row }">{{ row.personName }}</template>
          <template #beforefileSlot>
            <el-table-column label="审核状态" align="center" prop="checkStatus">
              <template #default="{ row }">
                {{ mapSatus[row.checkStatus] || "待审核" }}
              </template>
            </el-table-column>
            <el-table-column
              label="发布状态"
              width="200"
              prop="planState"
              align="center"
              key="planState"
            >
              <template #default="{ row }">
                {{ row.planState == 0 ? "已发布" : "未发布" }}
              </template>
            </el-table-column>
          </template>
          <template #fileSlot="{ row }">
            <el-button
              type="text"
              :disabled="!row.planImageFileUrl"
              @click="
                handleDownLoad(row.planImageFileUrl, row.planImageFileName)
              "
              >下载附件</el-button
            >
          </template>
          <template #actionButton="{ row }">
            <el-button
              type="text"
              style="width: 60px"
              v-if="row.checkStatus !== 2 && row.checkStatus !== 3"
              @click="handleExmiam(row)"
              v-hasPermi="['preventionPlan:updatePreventionPlanState']"
              >审核</el-button
            >
            <el-button
              type="text"
              v-if="row.checkStatus == 2"
              icon="Edit"
              @click="handleState(row)"
              >{{ row.planState == 0 ? "取消发布" : "发布" }}</el-button
            >

            <el-button
              type="text"
              icon="Edit"
              @click="handleEdit(row)"
              v-hasPermi="['preventionPlan:update']"
              >修改</el-button
            >
            <el-button
              type="text"
              icon="Delete"
              style="color: red"
              @click="handleDel(row)"
              v-hasPermi="['preventionPlan:delete']"
              >删除</el-button
            >
          </template>
        </Table>
        <DialogVform
          :formJson="formJson"
          ref="dialogVform"
          :slots="['deptName', 'userNames', 'fileSlot']"
          @onSubmit="onSubmit"
          title="隐患排查计划"
        >
          <template #deptName>
            <el-form-item label="责任部门" prop="deptId" label-position="right">
              <TreeSelect
                v-model="form.deptId"
                :options="deptTree"
                @change="changeDept"
                style="width: 100%"
              >
              </TreeSelect>
            </el-form-item>
          </template>
          <template #userNames>
            <el-form-item
              label="责任人"
              prop="userNames"
              label-position="right"
            >
              <el-input
                v-model="form.personName"
                readonly
                @click="onInnerOpen('personName')"
              >
              </el-input>
            </el-form-item>
          </template>
          <TableSelect
            ref="userTableSelect"
            :queryApi="listUser"
            :options="[]"
            :rowKey="'userId'"
            rowLabel="nickName"
            @onConfirm="onUserConfirm"
            rowLabelText="用户昵称"
          >
            <template #formSlot="{ handleQuery, filterForm }">
              <el-col :span="8">
                <el-form-item label="部门名称">
                  <el-input
                    size="small"
                    @change="handleQuery"
                    v-model="filterForm.deptName"
                    clearable
                    style="width: 100%"
                    @keyup.enter="handleQuery"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="用户名称">
                  <el-input
                    size="small"
                    @change="handleQuery"
                    v-model="filterForm.userName"
                    clearable
                    style="width: 100%"
                    @keyup.enter="handleQuery"
                  />
                </el-form-item>
              </el-col>
            </template>
            <template #default> </template>
            <template #tableSlot>
              <el-table-column
                label="部门"
                align="center"
                key="deptName"
                prop="dept.deptName"
              />
              <el-table-column
                label="用户名称"
                align="center"
                key="userName"
                prop="userName"
              />
              <el-table-column
                label="用户昵称"
                align="center"
                key="nickName"
                prop="nickName"
              />
            </template>
          </TableSelect>
          <template #fileSlot>
            <el-form-item label="文件上传" prop="fileId">
              <FileUpload
                :limit="1"
                :fileSize="30"
                :fileType="['png', 'jpeg', 'jpg']"
                v-model="files"
              ></FileUpload>
            </el-form-item>
          </template>
        </DialogVform>
      </el-col>
    </el-row>
    <el-dialog append-to-body v-model="shenheDialog" width="40%" title="审核">
      <template #default>
        <el-form label-width="100px" label-position="left">
          <el-form-item label="审核意见">
            <el-input type="textarea" v-model="shyj"></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="close">取 消</el-button>
          <el-button type="primary" @click="onExmiam(2)"> 通 过 </el-button>
          <el-button type="danger" @click="onExmiam(3)"> 拒 绝 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import Table from "@/components/Table/index.vue";
import SearchForm from "@/components/searchForm/index";
import DialogVform from "@/components/dialogVform/index";
import formJson from "./components/options.json";
import { apis as APIS } from "@/api/yhpc/yhpcjh.js";
import { useAsyncData, useFormJsonNew } from "@/views/hooks/useAsyncData.js";
import { deptTreeSelect, listUser } from "@/api/system/user";
import TableSelect from "@/components/tableSelect/index";
const { proxy } = getCurrentInstance();
const ops = useFormJsonNew(formJson, {
  sort: [],
  sortable: [],
});

const options = reactive({
  table: ops,
  formOps: ops.filter((i) =>
    ["planName", "checkType", "checkLevel"].includes(i.prop)
  ),
});
const showSearch = ref(true);
const dialogVform = ref();
const deptTree = ref([]);
const table = ref();
const userType = ref("");
const userTableSelect = ref();

const changeDept = (val, label) => {
  form.value.deptName = label;
  form.value.deptId = val;
};

// 补充修改.新增事件
const plugEdit = (row) => {
  form.value.deptName = row.deptName;
  form.value.deptId = row.deptId;
  form.value.userNames = row.userNames;
  form.value.userIds = row.userIds;
  form.value.personName = row.personName;
  form.value.personId = row.personId;
  if (row.planImageFileId) {
    files.value = [
      {
        name: row.planImageFileName,
        id: row.planImageFileId,
        url: row.planImageFileUrl,
      },
    ];
  }
};

const handleState = (row) => {
  proxy.$modal.confirm("是否确认操作 ？").then(() => {
    APIS.update({
      id: row.id,
      planState: row.planState == 1 ? 0 : 1,
    }).then(() => {
      getList();
    });
  });
};

const onInnerOpen = (type) => {
  userType.value = type;
  const { personName, personId } = form.value;
  let names = (personName && personName.split(",")) || [];
  let values = (personId && personId.split(",")) || [];

  userTableSelect.value.open(
    values.map((item, index) => ({
      value: values[index],
      label: names[index],
    }))
  );
};

const plugAdd = () => {
  files.value = [];
};
const onUserConfirm = (data) => {
  const values = data.map((item) => item.value);
  const names = data.map((item) => item.label);
  form.value.personId = values.join(",");
  form.value.personName = names.join(",");
};
const {
  onSubmit,
  fetchData,
  dialogType,
  handleAdd,
  handleEdit,
  getList,
  handleDel,
  queryParams,
  form,
  handleDownLoad,
} = useAsyncData({
  APIS,
  formJson,
  dialogVform,
  table,
  proxy,
  plugEdit,
  plugAdd,
});

onMounted(() => {
  deptTreeSelect().then((response) => {
    deptTree.value = response.data;
    console.log(deptTree.value);
  });
});
// 审核相关逻辑
const shyj = ref("");
const shRow = ref({});
const shenheDialog = ref(false);
const close = () => {
  shenheDialog.value = false;
};

const onExmiam = (checkStatus) => {
  if (shyj.value) {
    APIS.sh({
      examineOpinion: shyj.value,
      id: shRow.value.id,
      checkStatus,
    }).then((res) => {
      getList();
      close();
    });
  } else {
    proxy.$message.error("请输入审核意见");
  }
};

const handleExmiam = (row) => {
  shyj.value = "";
  shenheDialog.value = true;
  shRow.value = row;
};
const mapSatus = {
  1: "待审核",
  2: "已通过",
  3: "未通过",
};

// 文件
const files = ref([]);
watch(
  () => files,
  (newData) => {
    if (newData.value.length === 0) {
      form.value.planImageFileName = "";
      form.value.planImageFileId = "";
      form.value.planImageFileUrl = "";
    } else {
      form.value.planImageFileName = newData.value[0].name;
      form.value.planImageFileId = newData.value[0].id;
      form.value.planImageFileUrl = newData.value[0].url;
    }
  },
  {
    deep: true,
  }
);
</script>

<style lang="scss" scoped>
::v-deep.el-form-item__label {
  text-align: right !important;
}
</style>
